package Database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import Model.AuditLog;
import Model.Role;

public class AuditLogDB {

	/**
	 * @param args
	 */

	public static void insertLog(String action, String loginID) {
		Connection con = DBConnection.connect(true);
		PreparedStatement stmt = null;
		// Staff staff = new Staff();
		// HttpSession session = null;
		String select = "INSERT INTO auditlog(LoginID, Action) VALUES (?, ?)";

		try {
			stmt = con.prepareStatement(select);
			System.out.println(select);
			stmt.setString(1, loginID);
			stmt.setString(2, action);

			stmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
			}
		}
	}

	public static ArrayList<AuditLog> getAuditLog() {
		Connection con = DBConnection.connect(true);
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String select = "SELECT * FROM auditlog ORDER BY time desc";

		ArrayList<AuditLog> Arr = new ArrayList<AuditLog>();
		AuditLog al = null;

		try {
			stmt = con.prepareStatement(select);
			rs = stmt.executeQuery();
			while (rs.next()) {
				al = new AuditLog();
				al.setLoginId(rs.getString("LoginID"));
				al.setAction(rs.getString("Action"));
				al.setTime(rs.getString("time"));

				Arr.add(al);
			}
		} catch (Exception e) {
			e.printStackTrace();
			al = null;
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
			}
		}

		return Arr;
	}

	public static void clearAuditLog() {
		Connection con = DBConnection.connect(true);
		PreparedStatement stmt = null;
		String select = "DELETE FROM auditlog";

		try {
			stmt = con.prepareStatement(select);

			stmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
			}
		}
	}
}
